import axios from 'axios'
import Promise from 'bluebird'
import Cookies from 'js-cookie'

const handleResponse = (res) => {
  if (res.data.success) {
    $('#global_loading').hide()
    // 成功只返回data数据
    // return Promise.resolve(res.data.data)
    return Promise.resolve(res)
  } else {
    // status不为0为失败或错误情况
    return Promise.reject(res.data)
  }
}

export default {
  get (url, params) {
    params = params || {};
    var _xtbz = "xtbz" in params &&  params["xtbz"] || "";
    let queryString = []
    Object.keys(params).forEach(key => params[key] && queryString.push((`${key}=${params[key]}`)))
    if (queryString.length > 0) {
      queryString = queryString.join('&')
        if (url.indexOf('?') > -1) {
            url += `&${queryString}`
        } else {
            url += `?${queryString}`
        }
    }
    if(params['no_loading']) {
      $('#global_loading').hide()
    } else {
      $('#global_loading').show()
    }

    let _header = {
      'xtbz': _xtbz ? _xtbz : Cookies.get('platform_id') == 8 ? 'training' : 'cloud',//业务线标识
      'university-id' : Cookies.get('university_id'),  //将cookie中的university_id放入header中
      //'platform-id': Cookies.get('platform_id') || 0,
    };

    if(Cookies.get("dep") && url.indexOf("dep") == -1){
      var _dep = Cookies.get("dep");
      if(_dep) url = url.indexOf("?") != -1 ? url + "&dep=" + _dep : url + "?dep=" + _dep;
    }

    return axios
      .get(url,{
          headers: _header
      })
      .then(function (response, data) {
        return response
      })
      .then(handleResponse)
      .catch(error => {
        // 日志收集
        return Promise.reject(error)
      })
  },

  post (url, params) {
    params = params || {};
    if(params['no_loading']) {
      $('#global_loading').hide()
    } else {
      $('#global_loading').show()
    }

    let _header = {
      'xtbz': Cookies.get('platform_id') == 8 ? 'training' : 'cloud', //业务线标识
      'university-id' : Cookies.get('university_id'),  //将cookie中的university_id放入header中
      //'platform-id': Cookies.get('platform_id') || 0,
    };

    if(Cookies.get("dep") && url.indexOf("dep") == -1){
      var _dep = Cookies.get("dep");
      if(_dep) url = url.indexOf("?") != -1 ? url + "&dep=" + _dep : url + "?dep=" + _dep;
    }

    return axios
      .post(url, params,{
        headers : _header
      })
      .then(function (response, data) {
        $('#global_loading').hide()
        return response
      })
      .then(handleResponse)
      .catch(error => {
        return Promise.reject(error)
      })
  }
}
